/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.io.output.ByteArrayOutputStream;

import ru.irenproject.UiProtos.Page;
import ru.irenproject.UiProtos.TestDocumentEditorShape;
import ru.irenproject.it.ItOutput;
import ru.irenproject.it.ItProducer;
import ru.irenproject.it.ItWriter;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Stash;

import com.google.common.base.Predicate;
import com.google.protobuf.ByteString;
import com.google.protobuf.Message;

public final class TestDocumentEditor extends AbstractThing implements Visual, MarkableAsModified {
  public static final class SelectPageInput {
    public Page page;
  }

  public static final class ExportOutput {
    public byte[] test;
  }

  public static final class GetOutput {
    public byte[] test;
  }

  public static TestDocumentEditor createWithId(Test test, ByteString id) {
    TestDocumentEditor res = test.store().createWithId(TestDocumentEditor.class, id);
    res.prepare(test);
    return res;
  }

  @Stash private UiProtos.TestDocumentEditor.Builder $;
  private final ItOutput fItOutput;

  @Inject TestDocumentEditor(ItOutput itOutput) {
    fItOutput = itOutput;
  }

  private void prepare(Test test) {
    $.setTest(test.id())
     .setTestEditor(TestEditor.create(test).id())
     .setProfilesEditor(ProfilesEditor.create(test.profileList()).id())
     .setPage(Page.TEST)
     .setModified(false);
    testEditor().setProfileSupplier(profilesEditor().profileListEditor());
  }

  @Override public Message render() {
    TestDocumentEditorShape.Builder b = TestDocumentEditorShape.newBuilder();
    b.setPage($.getPage())
     .setModified($.getModified());

    switch ($.getPage()) {
      case TEST: {
        b.setTestEditor($.getTestEditor());
        break;
      }
      case PROFILES: {
        b.setProfilesEditor($.getProfilesEditor());
        break;
      }
    }

    return b.build();
  }

  @Action(markAsModified = false)
  public void doSelectPage(SelectPageInput in) {
    $.setPage(Check.inputNotNull(in.page));
  }

  private TestEditor testEditor() {
    return get($.getTestEditor(), TestEditor.class);
  }

  private ProfilesEditor profilesEditor() {
    return get($.getProfilesEditor(), ProfilesEditor.class);
  }

  private Test test() {
    return get($.getTest(), Test.class);
  }

  @Action(forgetChanges = true)
  public ExportOutput doExport() {
    deleteDisabledQuestions();
    deleteEmptySections();
    clearQuestionLabels();

    final Profile selectedProfile = profilesEditor().profileListEditor().profile();

    if (selectedProfile.hasLabelFilter()) {
      throw new BadInputException("Labels are not supported yet.");
    }

    selectedProfile.setTitle("");
    selectedProfile.clearLabelFilter();

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    fItOutput.writeDocument(new ItProducer() {
      @Override public void produce(ItWriter out) {
        out.setSkipImageSource();
        out.writeSectionTree(test().sectionTree());
        out.writeProfiles(Collections.singleton(selectedProfile));
      }
    }, stream);

    ExportOutput res = new ExportOutput();
    res.test = stream.toByteArray();
    return res;
  }

  private void deleteDisabledQuestions() {
    for (Section section : test().sectionTree()) {
      List<QuestionItem> disabled = new ArrayList<>();
      for (QuestionItem item : section.questionList()) {
        if (!item.enabled()) {
          disabled.add(item);
        }
      }

      section.questionList().removeItems(disabled);
    }
  }

  private void deleteEmptySections() {
    test().sectionTree().removeLeaves(new Predicate<Section>() {
      @Override public boolean apply(Section section) {
        return section.questionList().isEmpty();
      }
    });
  }

  private void clearQuestionLabels() {
    for (Section section : test().sectionTree()) {
      for (QuestionItem item : section.questionList()) {
        item.clearLabels();
      }
    }
  }

  @Action(markAsModified = false)
  public void doNop() {}

  @Action(markAsModified = false)
  public GetOutput doGet() {
    GetOutput res = new GetOutput();
    res.test = fItOutput.testToBytes(test());
    return res;
  }

  @Override public void setModified(boolean modified) {
    $.setModified(modified);
  }

  @Action(markAsModified = false)
  public void doMarkAsUnmodified() {
    $.setModified(false);
  }
}
